<template>
  <div class="customer-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.name" placeholder="请输入客户名称" clearable />
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="searchForm.contact" placeholder="请输入联系人" clearable />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="searchForm.phone" placeholder="请输入联系电话" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="暂停合作" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">总客户数</div>
            <div class="stats-value">{{ stats.totalCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">正常客户</div>
            <div class="stats-value">{{ stats.activeCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">暂停合作</div>
            <div class="stats-value">{{ stats.inactiveCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">本月新增</div>
            <div class="stats-value">{{ stats.monthlyNew || 0 }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-card class="action-card">
      <el-button type="primary" @click="handleAdd">新增客户</el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedIds.length">
        批量删除
      </el-button>
      <el-button type="warning" @click="handleExport">导出Excel</el-button>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        border
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="客户名称" width="200" />
        <el-table-column prop="contact" label="联系人" width="120" />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="address" label="地址" show-overflow-tooltip />
        <el-table-column prop="taxRate" label="税率" width="100">
          <template #default="{ row }">
            {{ row.taxRate ? row.taxRate + '%' : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '暂停合作' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="140">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="formData.contact" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="税率" prop="taxRate">
          <el-input-number
            v-model="formData.taxRate"
            :min="0"
            :max="100"
            :precision="2"
            placeholder="请输入税率"
          />
          <span class="unit">%</span>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="正常" :value="1" />
            <el-option label="暂停合作" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="客户详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="客户名称">{{ viewData.name }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ viewData.contact }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ viewData.phone }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ viewData.email }}</el-descriptions-item>
        <el-descriptions-item label="地址" :span="2">{{ viewData.address }}</el-descriptions-item>
        <el-descriptions-item label="税率">{{ viewData.taxRate ? viewData.taxRate + '%' : '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="viewData.status === 1 ? 'success' : 'danger'">
            {{ viewData.status === 1 ? '正常' : '暂停合作' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ formatDate(viewData.createTime) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { customerApi } from '@/api/crm/customer'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedIds = ref([])
const stats = reactive({
  totalCount: 0,
  activeCount: 0,
  inactiveCount: 0,
  monthlyNew: 0
})

// 搜索表单
const searchForm = reactive({
  name: '',
  contact: '',
  phone: '',
  status: ''
})

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogTitle = ref('新增客户')
const formRef = ref()
const formData = reactive({
  name: '',
  contact: '',
  phone: '',
  email: '',
  address: '',
  taxRate: null,
  status: 1
})
const viewData = reactive({})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入客户名称', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ]
}

// 获取数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    
    const response = await customerApi.list(params)
    
    if (response && response.code === 200 && response.data) {
      const page = response.data
      tableData.value = page?.records || []
      pagination.total = page?.total || 0
    } else {
      console.error('API返回错误:', response)
      ElMessage.error('获取数据失败：数据格式不正确')
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取客户数据失败:', error)
    ElMessage.error('获取数据失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const loadStats = async () => {
  try {
    const response = await customerApi.getStats()
    
    if (response && response.code === 200 && response.data) {
      const data = response.data
      Object.assign(stats, data)
    } else {
      console.error('统计数据响应格式错误:', response)
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
  loadStats()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    contact: '',
    phone: '',
    status: ''
  })
  pagination.current = 1
  loadData()
  loadStats()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增
const handleAdd = () => {
  console.log('新增客户') // 添加调试信息
  dialogTitle.value = '新增客户'
  Object.assign(formData, {
    id: '', // 确保新增时id为空
    name: '',
    contact: '',
    phone: '',
    email: '',
    address: '',
    taxRate: null,
    status: 1
  })
  console.log('表单数据已重置:', formData) // 添加调试信息
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  Object.assign(viewData, row)
  viewDialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  console.log('编辑客户数据:', row) // 添加调试信息
  dialogTitle.value = '编辑客户'
  
  // 清空表单数据，然后重新赋值
  Object.assign(formData, {
    id: '',
    name: '',
    contact: '',
    phone: '',
    email: '',
    address: '',
    taxRate: null,
    status: 1
  })
  
  // 将行数据赋值给表单
  Object.assign(formData, row)
  console.log('表单数据已更新:', formData) // 添加调试信息
  
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    console.log('删除客户:', row) // 添加调试信息
    await ElMessageBox.confirm('确定要删除这个客户吗？', '提示', {
      type: 'warning'
    })
    
    console.log('执行删除操作，客户ID:', row.id) // 添加调试信息
    const response = await customerApi.delete(row.id)
    
    console.log('删除API响应:', response) // 添加调试信息
    
    if (response && response.code === 200) {
      ElMessage.success('删除成功')
      loadData()
      loadStats()
    } else {
      ElMessage.error(response?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除客户失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要删除的客户')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 个客户吗？`, '提示', {
      type: 'warning'
    })
    
    const response = await customerApi.batchDelete(selectedIds.value)
    
    if (response && response.code === 200) {
      ElMessage.success('批量删除成功')
      loadData()
      loadStats()
    } else {
      ElMessage.error(response?.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除客户失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    console.log('提交表单数据:', formData) // 添加调试信息
    await formRef.value.validate()
    
    let response
    if (formData.id) {
      console.log('执行更新操作，客户ID:', formData.id) // 添加调试信息
      response = await customerApi.update(formData)
    } else {
      console.log('执行新增操作') // 添加调试信息
      response = await customerApi.add(formData)
    }
    
    console.log('API响应:', response) // 添加调试信息
    
    if (response && response.code === 200) {
      ElMessage.success(formData.id ? '更新成功' : '新增成功')
      dialogVisible.value = false
      loadData()
      loadStats()
    } else {
      ElMessage.error(response?.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败')
  }
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 导出
const handleExport = async () => {
  try {
    if (!tableData.value || tableData.value.length === 0) {
      ElMessage.warning('暂无数据可导出，请先加载数据')
      return
    }
    
    ElMessage.info('正在导出客户数据，请稍候...')
    
    // 准备CSV数据
    const headers = ['客户名称', '联系人', '联系电话', '邮箱', '地址', '税率', '状态', '创建时间']
    const dataList = []
    
    // 添加数据行
    tableData.value.forEach(row => {
      dataList.push([
        row.name || '',
        row.contact || '',
        row.phone || '',
        row.email || '',
        row.address || '',
        row.taxRate ? row.taxRate + '%' : '',
        row.status === 1 ? '正常' : '暂停合作',
        formatDate(row.createTime)
      ])
    })
    
    // 添加汇总行
    dataList.push([
      '总计',
      '',
      '',
      '',
      '',
      '',
      `记录数: ${pagination.total || 0}`,
      ''
    ])
    
    // 创建CSV文件并下载
    const workbook = new Blob([
      '\uFEFF' + // BOM for UTF-8
      headers.join(',') + '\n' +
      dataList.map(row => row.join(',')).join('\n')
    ], { type: 'text/csv;charset=utf-8;' })
    
    const url = window.URL.createObjectURL(workbook)
    const link = document.createElement('a')
    link.href = url
    link.download = `客户信息_${new Date().toISOString().slice(0, 10)}.csv`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败：' + error.message)
  }
}

// 工具函数
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  if (isNaN(d)) return String(date).slice(0, 10)
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

// 初始化
onMounted(() => {
  loadData()
  loadStats()
})
</script>

<style scoped>
.customer-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.stats-item {
  padding: 10px;
}

.stats-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.action-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.unit {
  margin-left: 8px;
  color: #666;
}
</style>
